package com.yenlien.traceyun.plant.controller;

import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.business.entity.Equipment;
import com.yenlien.traceyun.business.interceptor.UserAuthUtil;
import com.yenlien.traceyun.business.service.EquipmentService;
import com.yenlien.traceyun.common.utils.FileUtil;
import com.yenlien.traceyun.common.utils.RandomUtil;
import com.yenlien.traceyun.common.utils.Tools;
import com.yenlien.traceyun.plant.dao.KeBaiDao;
import com.yenlien.traceyun.plant.dao.ShiJiRuiTongDao;
import com.yenlien.traceyun.plant.dao.XinFengXiangDao;
import com.yenlien.traceyun.plant.dock_device.sjrt.GetCWDevData;
import com.yenlien.traceyun.plant.dock_device.sjrt.GetCWDevDataSF;
import com.yenlien.traceyun.plant.entity.ShiJiRuiTong;
import com.yenlien.traceyun.plant.dock_device.kebai.KeBaiData;
import com.yenlien.traceyun.plant.dock_device.xinfengxiang.XinFengXiang;
import com.yenlien.traceyun.plant.service.IotAppService;
import com.yenlien.traceyun.webase.controller.BaseController;
import com.yenlien.traceyun.webase.exception.BusinessException;
import com.yenlien.traceyun.webase.exception.ErrorPageException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.yenlien.traceyun.plant.dock_device.DevState.*;


/**
 * @Date 2022/12/13
 * @Author jiaLong
 * @Descript SASS物联网小程序   没有使用
 */
@RestController
@RequestMapping("/iotApp")
@Api(tags = "物联网小程序APP")
public class IOTAPPController extends BaseController {

    @Autowired
    private ShiJiRuiTongDao shiJiRuiTongDao;

    @Autowired
    private EquipmentService equipmentService;

    @Autowired
    private KeBaiDao keBaiDao;

    @Autowired
    private XinFengXiangDao xinFengXiangDao;

    @Autowired
    private IotAppService iotAppService;




    // 首页数据 没有使用
    @GetMapping(value = "/getDevData")
    @ApiOperation(value = "小程序设备首页数据,", notes = "可选参数：companyId(企业ID, 不传则使用当前账号所属企业)")
    public Object getDevData(String companyId) {
        return success(iotAppService.getDevData(companyId));
    }




    @GetMapping(value = "/getPlantData")
    @ApiOperation(value = "获取种植信息,", notes = "可选参数：companyId(企业ID, 不传则使用当前账号所属企业), plotId(地块ID, 不传则使用当前账号所属企业下的地块)")
    public Object getPlantData(String companyId, String plotId) {
        return success(iotAppService.getPlantData(companyId, plotId));
    }


    @GetMapping(value = "/getPlotByCompId")
    @ApiOperation(value = "获取该企业所有地块信息, 地块名称下拉列表", notes = "可选参数：companyId (不传就为当前登录账号所属企业)")
    public Object getPlotByCompId(String companyId) {
        return success(iotAppService.getPlotByCompId(companyId));
    }

    @GetMapping(value = "/getPlantBySoilId")
    @ApiOperation(value = "根据地块ID获取对应的种植信息已经农事操作信息", notes = "参数：soilId (地块id), 可选参数：plantName (种植名,模糊匹配)")
    public Object getPlantBySoilId(String soilId, String plantName) {
        return success(iotAppService.getPlantBySoilId(soilId, plantName));
    }










    // 获取所有设备
    @GetMapping(value = "/getAllDev")
    @ApiOperation(value = "获取所有设备,", notes = "可选参数：companyId(企业ID, 不传则使用当前账号所属企业)")
    private Object getAllDev(String companyId){
        return success(iotAppService.getAllDev(companyId));
    }



    // 根据设备类型获取设备列表
    @GetMapping(value = "/getDevListByType")
    @ApiOperation(value = "根据设备类型获取设备列表,", notes = "参数：devId(设备ID), 可选参数：companyId(企业ID, 不传则使用当前账号所属企业)")
    private Object getDevListByType(String devType, String companyId){
        if(StringUtils.isBlank(companyId)){
            companyId = UserAuthUtil.getLoginUser().getCompanyId();
        }
        String type = "气象监测站".equals(devType) ? EQU_TYPE_ENV : "土壤墒情站".equals(devType) ? EQU_TYPE_SOIL : EQU_TYPE_KILL_INSECT.equals(devType) ?
                EQU_TYPE_KILL_INSECT : "虫情测报仪".equals(devType) ?  EQU_TYPE_INSECT : "摄像头".equals(devType) ? "摄像头" : EQU_TYPE_WATER;
        // devType :    摄像头  土壤墒情  水质设备  气象传感    虫情监控   杀虫灯
        return success(equipmentService.findByCompanyId(companyId).stream().filter(x -> x.getType().equals(type)).collect(Collectors.toList()));
    }




    // 获取世纪瑞通播放地址
    @GetMapping(value = "/getVideoUrl")
    @ApiOperation(value = "获取世纪瑞通指定视频设备播放地址,", notes = "参数：devId(设备ID)")
    private Object getVideoUrl(String devId){
        Equipment equipment = equipmentService.findById(devId);
        String token = GetCWDevData.getToken(equipment.getAppKey(), equipment.getAppSecret());
        return success(GetCWDevData.getVideo(devId, token));
    }

    // 世纪瑞通视频旋转   其他设备则直接在页面上调用
    @GetMapping(value = "/videoMove")
    @ApiOperation(value = "世纪瑞通视频控制(其他设备则直接使用视频设备列表里的url),", notes = "参数：devId(设备ID), val(操作：Up:上；down:下；left:左；right:右；zoomin:放大；zoomout:缩小)")
    private Object videoMove(String devId, String val) {
        Equipment equipment = equipmentService.findById(devId);
        String token = GetCWDevData.getToken(equipment.getAppKey(), equipment.getAppSecret());
        return success(GetCWDevDataSF.videoMove(equipment.getSerial(), val, token));
    }





    // 获取历史数据
    @GetMapping(value = "/getHistoryData")
    @ApiOperation(value = "获取历史数据", notes = "参数：devId(设备ID), devType(设备类型), 可选参数：startTime (开始时间), endTime(结束时间)")
    public Object getHistoryData(String devId, String devType, String startTime, String endTime) {
        Equipment equipment = equipmentService.findByDevId(devId);
        if (EQU_MANUFACTURER_SJRT.equals(equipment.getManufacturer())) {
            if (EQU_TYPE_KILL_INSECT.equals(devType)) {
                if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime))
                    return success(shiJiRuiTongDao.getHistoryData(devId, startTime, endTime));
                else
                    return success(shiJiRuiTongDao.getHistoryData(devId));
            }
            if ("气象监测站".equals(devType) || "土壤墒情站".equals(devType)) {
                if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
                    return success(shiJiRuiTongDao.getHistoryData(equipment.getId(), startTime, endTime).stream().collect(Collectors.groupingBy(ShiJiRuiTong::getParamName)));
                } else {
                    return success(shiJiRuiTongDao.getHistoryData(equipment.getId()).stream().collect(Collectors.groupingBy(ShiJiRuiTong::getParamName)));
                }
            } else if ("虫情测报仪".equals(devType)) {
                if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
                    return success(shiJiRuiTongDao.getHistoryData(equipment.getId(), startTime, endTime));
                } else {
                    return success(shiJiRuiTongDao.getHistoryData(equipment.getId()));
                }
            }
        } else if (EQU_MANUFACTURER_XFX.equals(equipment.getManufacturer()) && "气象监测站".equals(devType)) {
            if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
                List<ShiJiRuiTong> shiJiRuiTongList = genXFXSjrtList(xinFengXiangDao.getHistoryData(equipment.getId(), startTime, endTime));
                return success(shiJiRuiTongList.stream().collect(Collectors.groupingBy(ShiJiRuiTong::getParamName)));
            } else {
                List<ShiJiRuiTong> shiJiRuiTongList = genXFXSjrtList(xinFengXiangDao.getHistoryData(equipment.getId()));
                return success(shiJiRuiTongList.stream().collect(Collectors.groupingBy(ShiJiRuiTong::getParamName)));
            }
        } else if (EQU_MANUFACTURER_KB.equals(equipment.getManufacturer()) && "气象监测站".equals(devType)) {
            if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
                List<ShiJiRuiTong> shiJiRuiTongList = genKBSjrtList(keBaiDao.getHistoryData(equipment.getId(), startTime, endTime));
                return success(shiJiRuiTongList.stream().collect(Collectors.groupingBy(ShiJiRuiTong::getParamName)));
            } else {
                List<ShiJiRuiTong> shiJiRuiTongList = genKBSjrtList(keBaiDao.getHistoryData(equipment.getId()));
                return success(shiJiRuiTongList.stream().collect(Collectors.groupingBy(ShiJiRuiTong::getParamName)));
            }
        }
        return fail("参数错误");
    }


    // 查询指定参数的历史数据
    @GetMapping(value = "/getHistoryDevData")
    @ApiOperation(value = "查询指定参数的历史数据", notes = "参数：devId(设备ID), paramName(参数名)，可选参数：startTime (开始时间), endTime(结束时间)")
    public Object getHistoryDevData(String devId, String paramName, String startTime, String endTime) {
        Equipment equipment = equipmentService.findByDevId(devId);
        if (EQU_MANUFACTURER_SJRT.equals(equipment.getManufacturer())) {
            return success(shiJiRuiTongDao.getHistoryData(devId, paramName, startTime, endTime));
        } else if (EQU_MANUFACTURER_XFX.equals(equipment.getManufacturer())) {
            return success(genXFXSjrtList(xinFengXiangDao.getHistoryData(equipment.getId(), paramName, startTime, endTime)));
        } else if (EQU_MANUFACTURER_KB.equals(equipment.getManufacturer())) {
            return success(genKBSjrtList(keBaiDao.getHistoryData(equipment.getId(), paramName, startTime, endTime)));
        }
        return fail("参数错误");
    }



    //  devType 1=气象监测站  2=土壤墒情站  5=杀虫灯
    @GetMapping(value = "/analysis")
    public Object Analysis(String devType, String yearMonth, String companyId){
        if(StringUtils.isBlank(companyId)){
            companyId = UserAuthUtil.getLoginUser().getCompanyId();
        }
        List<JSONObject> analysis = new ArrayList<>();
        if("1".equals(devType)){
            analysis = shiJiRuiTongDao.getAnalysis(yearMonth, devType, companyId);
        }
        analysis.addAll(keBaiDao.getAnalysis(yearMonth, companyId));
        analysis.addAll(xinFengXiangDao.getAnalysis(yearMonth, companyId));

        for(JSONObject json : analysis){
            String normal = "";
            String paramName = json.getString("paramName");
            if("空气湿度".equals(paramName))
                normal = "20~100%";
            if("光照强度".equals(paramName))
                normal = "0~1000000lux";
            if("大气压".equals(paramName))
                normal = "90~105kpa";
            if("空气温度".equals(paramName))
                normal = "-5~40℃";
            if("风速".equals(paramName))
                normal = "0~17.1m/s";
            if("风向".equals(paramName))
                normal = "0~360°";
            if("总辐射".equals(paramName))
                normal = "0~1000W/m2";
            if("降雨量".equals(paramName))
                normal = "0~100mm/min";

            if("土壤氮".equals(paramName) || "土壤磷".equals(paramName) || "土壤钾".equals(paramName))
                normal = "0~500mg/L";
            if("土壤PH".equals(paramName))
                normal = "0~16";
            if("土壤温度".equals(paramName))
                normal = "0~50℃";
            if("土壤湿度".equals(paramName))
                normal = "0~100%";
            if("土壤盐分".equals(paramName))
                normal = "0~5000mg/l";
            json.put("normal", normal);
        }
        return success(analysis.stream().filter(Objects::nonNull).collect(Collectors.toList()));
    }


    // 图形汇总下面的图表
    @GetMapping(value = "/line")
    public Object line(String paramName, String yearMonth, String companyId){
        if(StringUtils.isBlank(companyId)){
            companyId = UserAuthUtil.getLoginUser().getCompanyId();
        }
        List<JSONObject> lineList = new ArrayList<>();
        lineList.addAll(shiJiRuiTongDao.getLine(yearMonth, paramName, companyId));
        lineList.addAll(keBaiDao.getLine(yearMonth, paramName, companyId));
        lineList.addAll(xinFengXiangDao.getLine(yearMonth, paramName, companyId));
        Map<String, List<JSONObject>> cTime = lineList.stream().collect(Collectors.groupingBy(x -> x.getString("cTime")));
        return success(cTime);
    }









    public static final String ROOT = "fruitUpload";
    @Autowired
    private ResourceLoader resourceLoader;


    @RequestMapping(value = "/show/{filename:.+}")
    public void loadFile(@PathVariable("filename") String filename, HttpServletRequest request, HttpServletResponse response) throws IOException, ErrorPageException {
        BufferedInputStream in = null;
        ByteArrayOutputStream bos = null;
        String ys = request.getParameter("ys");
        try {
            File file = resourceLoader.getResource("file:" + Paths.get(ROOT, filename).toString()).getFile();
            bos = new ByteArrayOutputStream();
            String suf = FileUtil.getSuffix(filename).toLowerCase();
            in = new BufferedInputStream(new FileInputStream(file));
            int buf_size = 1024;
            byte[] buffer = new byte[buf_size];
            int len = 0;
            while (-1 != (len = in.read(buffer, 0, buf_size))) {
                bos.write(buffer, 0, len);
            }
            if (suf.contains("png") || suf.contains("jpg") || suf.contains("gif") || suf.contains("JPEG")) {
                response.setContentType("image/png");
            } else {
                response.setHeader("content-type", "application/octet-stream");
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            }
            response.getOutputStream().write(bos.toByteArray());
        } catch (IOException e) {
            throw new ErrorPageException("文件【" + filename + "】不存在");
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public String upload(MultipartFile file) {
        File destFile = new File(Paths.get(ROOT).toAbsolutePath().toString());
        if (!destFile.exists()) {
            destFile.mkdirs();
        }
        String type = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));// 取文件格式后缀名
        String filename = System.currentTimeMillis() + "_" + RandomUtil.random(6) + type;// 取当前时间戳作为文件名
        File sourceFile = new File(Paths.get(ROOT, filename).toAbsolutePath().toString());
        try {
            file.transferTo(sourceFile);
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException("保存文件失败");
        }
        return filename;
    }





    public List<ShiJiRuiTong> genXFXSjrtList(List<XinFengXiang> historyData) {
        List<ShiJiRuiTong> shiJiRuiTongList = new ArrayList<>();
        for (XinFengXiang xinFengXiang : historyData) {
            ShiJiRuiTong sjrt = new ShiJiRuiTong();
            sjrt.setCtime(Tools.DATE_TIME_FORMAT.format(xinFengXiang.getDateTime()));
            sjrt.setEquipmentId(xinFengXiang.getEquipmentId());
            sjrt.setParamVal(xinFengXiang.getEValue());
            sjrt.setParamName(xinFengXiang.getEName());
            sjrt.setParamUnit(xinFengXiang.getEUnit());
            shiJiRuiTongList.add(sjrt);
        }
        return shiJiRuiTongList;
    }

    public List<ShiJiRuiTong> genKBSjrtList(List<KeBaiData> historyData) {
        List<ShiJiRuiTong> shiJiRuiTongList = new ArrayList<>();
        for (KeBaiData keBaiData : historyData) {
            ShiJiRuiTong sjrt = new ShiJiRuiTong();
            sjrt.setCtime(keBaiData.getThattime().toString());
            sjrt.setEquipmentId(keBaiData.getEquipmentId());
            sjrt.setParamVal(keBaiData.getSenval());
            sjrt.setParamName(keBaiData.getSensorname());
            sjrt.setParamUnit(keBaiData.getUnit());
            shiJiRuiTongList.add(sjrt);
        }
        return shiJiRuiTongList;
    }



}
